<script setup>
import { ref, reactive, computed, nextTick } from 'vue';
// 导入子组件（路径不变）
import sqtz from "./tuizhupage/shenqingtuizhu.vue";
import sqsp from "./tuizhupage/shenqingshenpi.vue";
import spjg from "./tuizhupage/shenpijieguo.vue";
import jiechu from "./tuizhupage/jiechuhetong.vue";
import jiechuMsg from "./tuizhupage/jiechuhetongMsg.vue";
import tzzd from "./tuizhupage/tiaozhengzhangdan.vue";
import tzzdMsg from "./tuizhupage/tiaozhengzhangdanMsg.vue";
import fyqs from "./tuizhupage/feiyongqingsuan.vue";
import msg from "./tuizhupage/msgshow.vue";
import sqclz from "./tuizhupage/shenpichulizhong.vue";
import { useRoute } from 'vue-router';
import { listAccraditationRecord } from "@/api/le/accraditationRecord"
import { useUserStore } from '@/store/modules/user'
import { useRouter } from "vue-router";
// 获取路由实例
const router = useRouter();
// 原始数据结构保留
const userStore = useUserStore()
const route = useRoute();
const accraditationRecord = ref({});
const pending = ref(null);
const query = route.query.ptStr;
if (query) {
  pending.value = JSON.parse(query);
  console.log("待办任务信息：", pending.value);

}

const allMessage = reactive({
  checkOutManagementId: pending.value?.bussniessId || '',
  daibanMsg: {},
  shenqingMsg: {
    checkOutManagementId: "",
    elderlyName: "",
    idCard: "",
    phone: "",
    feeStartTerm: '',
    feeEndTerm: '',
    nursingLevel: "",
    bed: "",
    contract: "",
    elderAdvisor: "",
    nursingStaff: [],
    checkoutDate: "",
    checkoutReason: "",
    remark: "",
    creator: "",
    createDate: ""
  },
  jiechuForm: {},
  shenpiForm: {
    result: "",
    reason: "",
  }
});

// 角色定义
const role = ref({
  roleId: 0
});

// 订单状态与步骤配置
const management = ref({
  orderStatus: pending.value ? Number(pending.value.stepNo) : 1
});
const step = reactive([
  { stepId: "1", stepText: "申请退住" },
  { stepId: "2", stepText: "申请审批" },
  { stepId: "3", stepText: "解除合同" },
  { stepId: "4", stepText: "退住审批" }
]);

// 当前显示步骤
const displayStep = ref(
  management.value.orderStatus ? management.value.orderStatus.toString() : "-1"
);
// 核心计算属性
console.log("roleId",role.value.roleId);

const isApproverRole = computed(() => role.value.roleId == 1);
const isNormalRole = computed(() => role.value.roleId == 0);
const isNormalShowSqclz = computed(() => {
  return isNormalRole.value && [2, 4].includes(Number(displayStep.value));
});

// 新增：判断当前是否显示需要提交的组件（核心逻辑）
const isShowSubmitComponents = computed(() => {
  if (!isApproverRole.value) return false; // 仅审批角色适用

  // 匹配需要显示提交按钮的步骤
  const submitSteps = ['1', '2','3', '4']; // sqtz、jiechu、fyqs对应的步骤
  const sqspSteps = [2, 4]; // sqsp对应的步骤

  return submitSteps.includes(displayStep.value) || sqspSteps.includes(Number(displayStep.value));
});

// 原始步骤状态判断保留
const isStepActive = (stepId) => {
  return Number(stepId) <= Number(management.value.orderStatus);
};
const isStepClickable = (stepId) => {
  return Number(stepId) <= Number(management.value.orderStatus);
};
const isLineActive = (index) => {
  return Number(management.value.orderStatus) > index + 1;
};

// 角色获取逻辑
const getRole = () => {
  if (pending.value) {
    // console.log("进入角色身份验证函数");

    listAccraditationRecord({
      bussniessId: pending.value.bussniessId,
      stepNo: pending.value.stepNo - 1
    }).then(response => {
      const records = response.rows || [];
      console.log("res",response);
      
      const isApprover = (records.length > 0 && userStore.id === records[0].nextApproverId)|| records[0].nextApproverId==null;
      accraditationRecord.value = records[0];
      // console.log("页面获取的审批记录",accraditationRecord.value);
      
      role.value.roleId = isApprover ? 1 : 0;
      nextTick(() => {
        displayStep.value = management.value.orderStatus.toString();
      });
        // console.log("角色身份", role.value.roleId);

    }).catch(error => {
      // console.error("获取审批记录失败：", error);
      role.value.roleId = 0;
    });
  } else {
    role.value.roleId = 0;
  }

};
getRole();

// 事件处理逻辑
const handleUpdateForm = (formData) => {
  allMessage.checkOutManagementId = formData.checkOutManagementId;
  allMessage.shenqingMsg = formData;
  pending.value = formData.pending;
  // console.log("index页面获取申请页面的pending", pending.value);
  displayStep.value = formData.step;
};

const handleStepClick = (stepId) => {
  if (isStepClickable(stepId)) {
    displayStep.value = stepId;
  }
};

const handleBack = () => {
  // const current = Number(displayStep.value);
  // if (current > 1) {
  //   displayStep.value = (current - 1).toString();
  // }
        router.push({ path: "/xietong/pendingTasks", 
             });
};

// 下一步按钮逻辑
const handleNextStep = () => {
  const current = Number(displayStep.value);
  if (current < step.length) {
    displayStep.value = (current + 1).toString();
  }
};

// 子组件引用与提交逻辑
const sqspRef = ref(null);
const sqtzRef = ref(null);
const jiechuRef = ref(null);
const zhangdanRef = ref(null);

// 提交按钮逻辑
const handleSubmit = async () => {
  try {
    if ((displayStep.value === '1' && isApproverRole.value) || !pending.value) {
      sqtzRef.value?.handleSubmit();
      console.log("调用申请退住的提交按钮");
      //在提交逻辑中，等待sqtzRef反馈数据
    } else if ([2, 4].includes(Number(displayStep.value)) && isApproverRole.value) {
      allMessage.shenpiForm = await sqspRef.value?.submitApprovalForm();
    } else if (displayStep.value === '3' && isApproverRole.value) {
      allMessage.jiechuForm = await jiechuRef.value?.handleSubmit();
      
    }    
    const current = Number(displayStep.value);
    if (current < step.length) {
      displayStep.value = (current + 1).toString();
    }
  } catch (error) {
    console.error('提交失败：', error.message);
  }
};
</script>


<template>
  <div class="father_contain">
    <div class="head">
      <div class="steps-container">
        <div v-for="(item, index) in step" :key="index" class="step-wrapper">
          <div class="step" :class="{
            active: isStepActive(item.stepId),
            clickable: isStepClickable(item.stepId)
          }" @click="handleStepClick(item.stepId)">
            <div class="step-number">{{ item.stepId }}</div>
            <div class="step-text">{{ item.stepText }}</div>
          </div>
          <div class="step-divider" :class="{ 'divider-active': isLineActive(index) }" v-if="index < step.length - 1">
          </div>
        </div>
      </div>
    </div>

    <div class="main">
      <div class="left">
        <!-- 普通用户显示sqclz的场景 -->
        <sqclz v-if="isNormalShowSqclz && displayStep == management.orderStatus" ref="sqspRef" :shenpiform="accraditationRecord" />

        <!-- 其他场景 -->
        <template v-else>
          <sqtz v-if="!pending" @updateSubmitForm="handleUpdateForm" ref="sqtzRef" />
          <jiechu v-if="displayStep === '3' && isApproverRole && management.orderStatus==3" ref="jiechuRef" :Lastfrom="pending"/>

          <msg v-if="displayStep >= 1 && management.orderStatus > 1" :all-message="allMessage" />
          <jiechuMsg v-if="management.orderStatus > 3 && displayStep >=3" :Lastfrom = "pending" />
          <!-- <tzzdMsg v-if="displayStep > 4" /> -->
        </template>
      </div>

      <div class="right">
        <template v-if="!isNormalShowSqclz">
          <sqsp v-if="[2,4].includes(Number(displayStep)) && isApproverRole && [2,4].includes(Number(management.orderStatus)) && management.orderStatus == displayStep  && pending.isHandle == 0" ref="sqspRef" :Lastfrom="pending" :currentStep="displayStep"
            :shenpiform="accraditationRecord" />
          <spjg v-if="[2,4].includes(Number(displayStep)) && management.orderStatus > displayStep" ref="sqspRef" :Lastfrom="pending" :currentStep="displayStep"
            :shenpiform="accraditationRecord" />
          <!-- <spjg v-if="(displayStep == 4 || displayStep == 2)  && management.orderStatus == 5 " ref="sqspRef" :Lastfrom="pending"
            :shenpiform="accraditationRecord" /> -->
        </template>
      </div>
    </div>

    <div class="footer">
      <button class="footer-btn" @click="handleBack">返回</button>

      <!-- 核心：根据是否显示指定组件切换按钮 -->
      <template v-if="(isApproverRole && !isNormalShowSqclz) || (!pending)">
        <!-- 显示sqtz/jiechu/tzzd/fyqs/sqsp时显示提交按钮 -->
        <button class="footer-btn" @click="handleSubmit" v-if="isShowSubmitComponents || (!pending)">
          提交
        </button>

        <!-- 其他场景显示下一步按钮（最后一步不显示） -->
        <button class="footer-btn" @click="handleNextStep" v-else-if="Number(displayStep) < step.length">
          下一步
        </button>
      </template>
    </div>
  </div>
</template>

<style scoped>
/* 完全保留原始样式 */
.father_contain {
  padding: 10px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.head {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  box-sizing: border-box;
}

.steps-container {
  display: flex;
  align-items: center;
  width: 100%;
  overflow: hidden;
  padding: 10px 0;
}

.step-wrapper {
  display: flex;
  align-items: center;
  flex: 1;
  position: relative;
}

.left {
  width: 50%;
}

.right {
  width: 40%;
  margin-top: 20px;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;
  transition: all 0.3s;
}

.step-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.step-text {
  font-size: 12px;
  white-space: nowrap;
  transition: all 0.3s;
}

.step:not(.active) .step-number {
  border: 1px solid #ddd;
  color: #999;
  background-color: #fff;
}

.step:not(.active) .step-text {
  color: #999;
}

.step.active .step-number {
  background-color: #007bff;
  color: #fff;
  border: 1px solid #007bff;
}

.step.active .step-text {
  color: #007bff;
  font-weight: 500;
}

.step.clickable {
  cursor: pointer;
}

.step.clickable:hover .step-number {
  transform: scale(1.1);
  box-shadow: 0 0 8px rgba(0, 123, 255, 0.3);
}

.step.clickable:hover .step-text {
  text-decoration: underline;
}

.step-divider {
  height: 2px;
  flex: 1;
  background-color: #ddd;
  transition: all 0.3s;
  min-width: 20px;
}

.divider-active {
  background-color: #007bff;
}

.main {
  width: 100%;
  min-height: 400px;
  display: flex;
  padding: 20px;
  justify-content: space-between;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  margin-bottom: 15px;
  box-sizing: border-box;
}

.main>* {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0;
}

.footer-btn {
  padding: 8px 20px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.footer-btn:nth-child(1) {
  background-color: #eee;
  color: #333;
}

.footer-btn:nth-child(1):hover {
  background-color: #ddd;
}

.footer-btn:nth-child(2) {
  background-color: #007bff;
  color: #fff;
}

.footer-btn:nth-child(2):hover {
  background-color: #0056b3;
}

@media (max-width: 768px) {
  .step-text {
    font-size: 10px;
  }

  .step-number {
    width: 24px;
    height: 24px;
    font-size: 14px;
  }

  .steps-container {
    padding: 5px 0;
  }

  .main {
    flex-direction: column;
  }

  .left,
  .right {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>